import React, {Component} from 'react';
import { Card, Button, Select, Input, Table, message  } from 'antd';
import {PlusOutlined} from "@ant-design/icons";
import {reqProductList,reqSearchNameOrDesc,reqProductUpdateStatus} from '../../api/index.js'

//每页条目数
import {paginationSize} from '../../config/index.js'

const { Option } = Select;

class Product extends Component {
  state = {
    pageNum: 1,  //页码
    dataSource: [],  //获取商品分页列表数据
    productNameOrDesc: 'productName',  //选择的是商品名称/描述
    total: 0,
  };
  inputContent = React.createRef()
  render() {
    const {dataSource,total} = this.state
    
    // table行配置
    const columns = [
      {
        title: '商品名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '商品描述',
        dataIndex: 'desc',
        key: 'desc',
      },
      {
        title: '价格',
        dataIndex: 'price',
        key: 'price',
        render: (value) => {
          return '￥' + value
        }
      },
      {
        title: '状态',
        render: (value) => {
          // 1在售，2已下架
          return <div>
            <Button type={value.status === 1 ? 'danger' : 'primary'} onClick={this.UpdateStatus.bind(this,value)}>{value.status === 1 ? '下架' : '上架'}</Button>
            <div>{value.status === 1 ? '在售': '已下架'}</div>
          </div>
        }
      },
      {
        title: '操作',
        render: (value) => {
          return <div>
            <Button type="link" onClick={this.goDetail.bind(this,value)}>详情</Button>
            <Button type="link" onClick={this.goAddUpdate.bind(this,value)}>修改</Button>
          </div>
        }
      },
    ];
    return <div>
      <Card
        title={
          <div>
            <Select defaultValue="Name" style={{ width: 120 }} onChange={this.selectedNameOrDesc}>
              <Option value="Name">按名称搜索</Option>
              <Option value="desc">按描述搜索</Option>
            </Select>
            <Input
              onChange={this.InputChange}
              ref={this.inputContent}
              placeholder="关键字"
              style={{marginLeft:10,marginRight:10, width: '25%'}}
              allowClear
            />
            <Button type="primary" onClick={this.search}>搜索</Button>
          </div>
        }
        extra={<Button onClick={this.goAddUpdate.bind(this, null)} type="primary" icon={<PlusOutlined/>}>添加商品</Button>}
      >
        {/*table表格*/}
        <Table
          dataSource={dataSource}
          columns={columns}
          bordered
          rowKey="_id"
          pagination={{
            total:total,
            onChange:this.changePagination,
            defaultPageSize:paginationSize
          }}
        />
      </Card>
    </div>
  }
  
  componentDidMount() {
    // 获取商品分页列表
    this.getProductList()
  }
  
  // 获取商品分页列表
  getProductList = async () => {
    let {pageNum} = this.state;
    let res = await reqProductList({pageNum,pageSize:paginationSize});
    let {status,data,msg} = res;
    if(status === 0) {  // 请求成功
      this.setState({
        dataSource: data.list,
        total: data.total
      })
    } else{ // 请求失败
      message.error(msg, 1)
    }
  }
  
  // selected选择name/desc
  selectedNameOrDesc = (value) => {
    if (value === 'name') {   //根据Name搜索产品分页列表
      this.setState({
        productNameOrDesc: 'productName'
      })
    } else {   //根据desc搜索产品分页列表
      this.setState({
        productNameOrDesc: 'productDesc'
      })
    }
  }
  
  // 根据Name/desc搜索产品分页列表
  search = async () => {
    let searchContent = this.inputContent.current.input.value
    let {pageNum,productNameOrDesc} = this.state
    let res = await reqSearchNameOrDesc({pageNum,pageSize:paginationSize,productNameOrDesc,searchContent})
    let {data, status, msg} = res
    if (status === 0){  //获取数据成功
      this.setState({
        dataSource: data.list,
        total: data.total
      })
      message.success('数据获取成功！',1)
    } else {  //获取数据失败
      message.warning(msg, 1)
    }
    
  }
  
  // input输入框清零时，重新获取商品分页列表，恢复默认table表格数据
  InputChange = (e) => {
    if (!e.target.value){
      // 获取商品分页列表
      this.getProductList()
    }
  }
  
  // 改变页码
  changePagination = (pageNum) => {
    this.setState({
      pageNum
    },function () {
      let value = this.inputContent.current.input.value
      if (value) {   // 搜索分页
        this.search()
      } else {   // 普通分页
        // 获取商品分页列表
        this.getProductList()
      }
    })
  }
  
  // 对商品进行上架/下架处理
  UpdateStatus = async (value) => {
    let {_id,status} = value
    status = status === 1 ? 2 : 1
    let res = await reqProductUpdateStatus({productId:_id,status})
    if (res.status === 0) {  //请求成功
      let dataSource = [...this.state.dataSource]
      dataSource.forEach(item => {
        if (item._id === _id) {
          return item.status = status
        }
      })
      this.setState({dataSource})  //更新dataSource
      message.success('状态更新成功',1)
    } else {  //请求失败
      message.success(res.msg,1)
    }
  }
  
  // 点击添加商品按钮，跳转添加商品页面
  goAddUpdate = (value) => {
    if (value) {  //修改跳转，将数据传给修改页面
      this.props.history.push('/admin/prod_about/product/addUpdate',value)
    } else {// 添加跳转，不需要传数据
      this.props.history.push('/admin/prod_about/product/addUpdate')
    }
  }
  
  // 点击详情修改，跳转到详情修改页面
  goDetail = (value) => {
    this.props.history.push(`/admin/prod_about/product/detail/${value._id}`)
  }
}

export default Product;
